package com.ceo.common.i18.util;

import com.ceo.common.i18.domain.LangEnv;
import com.ceo.common.i18.domain.LanguageTypeEnum;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/22 16:27
 * Copyright (c)  All rights reserved
 */
@Component
public class LanguageTransUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(LanguageTransUtil.class);

    private static LanguageTransUtil staticInstance = new LanguageTransUtil();
    private static MessageSourceAccessor accessor;
    private static String baseName;

    @Value("${application.i18n.basename}")
    public String baseName_yml;

    @PostConstruct
    public void CopyConfig() {
        LOGGER.debug("多语言工具初始化完成:" + baseName_yml);
        staticInstance.baseName = baseName_yml;
    }

    /**
     * 初始化资源文件的存储器
     * 加载指定语言配置文件
     */
    private static void initMessageSourceAccessor() {
        ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
        if (Strings.isEmpty(staticInstance.baseName)) {
            LOGGER.warn("未配置多语言地址");
        } else {
            String[] baseNames = staticInstance.baseName.split(",");
            // 调试打印，发布删除
            reloadableResourceBundleMessageSource.setBasenames(baseNames);
        }
        reloadableResourceBundleMessageSource.setCacheSeconds(1800);
        reloadableResourceBundleMessageSource.setDefaultEncoding("UTF-8");
        accessor = new MessageSourceAccessor(reloadableResourceBundleMessageSource);
    }

    /**
     * @param language 语言类型,zh_cn: 简体中文, en_us: 英文
     * @param code     配置信息属性名,eg: api.response.code.user.signUp
     * @return 返回国际化后的语言
     */
    public static String getMessage(String language, String code) {
        initMessageSourceAccessor();
        return accessor.getMessage(code, "invalid error code", LanguageTypeEnum.getLanguageLocale(language));
    }

    /**
     * @param code 配置信息属性名
     * @return 返回国际化后的语言
     */
    public static String getMessage(String code) {
        String tmp = getMessage(LanguageTypeEnum.getLanguageType(LangEnv.getLangEnc())
                , code);
        return tmp;
    }
}
